﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LandandSurvey
{
    public partial class EditUser : System.Web.UI.Page
    {
        protected void Page_Load( object sender, EventArgs e )
        {
            if ( !IsPostBack )
            {
                using ( landsdbEntities context = new landsdbEntities() )
                {
                    int id = Convert.ToInt16( Request[ "id" ] );
                    AppUser user = ( from i in context.AppUsers
                                     where i.Id == id
                                     select i ).FirstOrDefault();

                    txtUsername.Text = user.UserName;
                    chkEdit.Checked = user.EditAbout;
                    chkUpload.Checked = user.UploadFiles;
                    chkAdmin.Checked = user.IsAdmin;
                }
            }
        }

        protected void btnSave_Click( object sender, EventArgs e )
        {
            using ( landsdbEntities context = new landsdbEntities() )
            {
                int id = Convert.ToInt16( Request[ "id" ] );
                AppUser appuser = ( from i in context.AppUsers
                                    where i.Id == id
                                    select i ).FirstOrDefault();

                if ( txtNewPasswod.Text.Trim() != string.Empty && txtConfirmPassword.Text.Trim() != string.Empty )
                {
                    if ( appuser.Password == txtOldPassword.Text )
                    {
                        appuser.Password = txtNewPasswod.Text;
                    }
                }

                appuser.UploadFiles = chkUpload.Checked;
                appuser.EditAbout = chkEdit.Checked;
                appuser.IsAdmin = chkAdmin.Checked;

                context.AppUsers.ApplyCurrentValues( appuser );
                try
                {
                    context.SaveChanges();
                    Response.Redirect( "ViewUsers.aspx" );
                }
                catch
                {
                    lblMessage.InnerText = "An error occured while saving the user record.";
                }
            }
        }
    }
}